package com.sl.au.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Option;
import com.sl.au.entity.SocketMessage;
import com.sl.au.entity.TransferTask;
import com.sl.au.config.AppWebSocketTask;
import com.sl.au.entity.Account;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.EventType;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.EventToEvaluateUser;
import com.sl.au.entity.Module;
import com.sl.au.entity.ViewForEventReportTask;
import com.sl.au.service.OptionService;
import com.sl.au.service.TransferTaskService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.GradingService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.EventToEvaluateUserService;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 事件源
 * 
 * @author LK
 *
 */
@RestController
@RequestMapping(value = "/ui/eventReport")
public class EventReportController extends BaseController {
	private int page;
	private int row;

	public int getRow() {
		return row;
	}

	public void setRow(int row) {
		this.row = row;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	@Autowired
	private EventTypeService eventTypeService;
	@Autowired
	private EventReportService eventReportService;
	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private GradingService gradingService;
	@Autowired
	private EventToEvaluateUserService eventToEvaluateUserService;

	@Autowired
	private OperateLogService operateLogService;

	@Autowired
	private GridAreaInfoService gridAreaInfoService;

	@Autowired
	private IdentifyService identifyService;
	
	@Autowired
	private TransferTaskService transferTaskService;

	@RequestMapping("/findById/{id}")
	public MsgHelper findById(@PathVariable("id") String id) {
		return MsgHelper.success().put("info", eventReportService.getRepository().findOne(id));
	}

	@RequestMapping("/findInitedInfo")
	public Map<String, Object> findInitedInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String id = request.getParameter("needId");
		EventReport report = eventReportService.getRepository().findOne(id);
		double latitude = report.getLatitude();
		double longitude = report.getLongitude();
		String addr = report.getReportAdress();
		EventType eventType = report.getReportEventType();
		List<EventReport> list = eventReportService.findInitedInfo(start, length, id, latitude, longitude, eventType,
				addr);
		int count = eventReportService.findInitedInfoCount(id, latitude, longitude, eventType, addr);
		map.put("data", list);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// public MsgHelper findInitedInfo(@PathVariable("id") String id) {
	// EventReport report = eventReportService.getRepository().findOne(id);
	// double latitude = report.getLatitude();
	// double longitude = report.getLongitude();
	// EventType eventType = report.getReportEventType();
	// List<EventReport> list = eventReportService.findInitedInfo(id, latitude,
	// longitude, eventType);
	// return MsgHelper.success().put("list", list);
	// }

	@RequestMapping("/getProcedure/{reportId}")
	public MsgHelper getProcedure(@PathVariable("reportId") String reportId) {
		List<EventTask> procedures = eventReportService.findProcedures(reportId);
		return MsgHelper.success().put("procedures", procedures);
	}

	@RequestMapping("/getTransfer/{reportId}")
	public MsgHelper getTransfer(@PathVariable("reportId") String reportId) {
		List<TransferTask> procedures = transferTaskService.getRepository().getNewestTaskByEventId(reportId);
		return MsgHelper.success().put("procedures", procedures);
	}

	@RequestMapping("/findEventTypeById/{id}")
	public MsgHelper findEventTypeById(@PathVariable("id") String pid) {

		// 移动端判断是否具有事件登记权限
		Boolean isRegister = false;
		Account account = this.getMyAccount();
		for (Module m : account.getRole().getModules()) {
			if ("eventRegister".contains(m.getTarget().replace("?device=mobile", ""))) {
				isRegister = true;
				break;
			}
			if (!m.getTarget().equals("#")) {
				String model = m.getTarget().split("/")[2];
				if ("eventRegister".contains(model))
					isRegister = true;
			}
		}
		MsgHelper helper = MsgHelper.success().put("isRegister", isRegister);

		if (isRegister) {
			List<EventType> eventTypesHasChild = this.eventTypeService.getRepository()
					.getEventTypesHasChildByParent(pid);
			List<EventType> eventTypesHasNoChild = this.eventTypeService.getRepository()
					.getEventTypesHasNoChildByParent(pid);

			helper.put("eventTypesHasChild", eventTypesHasChild);
			helper.put("eventTypesHasNoChild", eventTypesHasNoChild);
		}

		return helper;
	}

	@RequestMapping(value = "/saveReportAndRegisterEvent", method = RequestMethod.POST)
	public Map<String, Object> saveReportAndRegisterEvent(MultipartHttpServletRequest requests) {
		MultipartFile file = requests.getFile("file");
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;

		// 获取当前EventReport图片的存储路径
		String url = "";
		if (file != null && !file.isEmpty()) {
			// 注意路径的构建
			url = getUploadFilePath(this.fileUploadPath, "img/eventReport", file);
		}
		JSONObject project = JSONObject.fromObject(request.getParameter("eventReport"));
		EventReport eventReport = (EventReport) JSONObject.toBean(project, EventReport.class);
		//标注事件来源
		Option org=this.optionService.getRepository().findByGroupAndExtended1("事件上报来源", "移动端");
		if(org!=null){
			eventReport.setReportEventOrg(org);
		}
		//------------
		// 前端图片压缩上传功能
		if (eventReport.getReportImgAdress() != null
				&& eventReport.getReportImgAdress().contains("data:image/png;base64")) {
			String[] imgl = eventReport.getReportImgAdress().split(",");
			eventReport.setReportImgAdress("");
			url = this.saveImgWithBase64(this.fileUploadPath, "img/eventReport", eventReport.getId() + ".png",
					imgl[imgl.length - 1]);
		}
		// -----------------------

		EventTask reportTask = null;
		if (this.eventRegisterService.getRepository().findOne(eventReport.getId()) == null) {
			reportTask = new EventTask();
			reportTask.setEventId(eventReport.getId());
			reportTask.setEventTaskTime(DateTime.now().toDate());
			reportTask.setEventTaskUser(this.getMyAccount().getUser());
		}

		// 设置事件上报其他信息.
		eventReport.setReportImgAdress(url);
		eventReport.setReportAccTime(DateTime.now().toDate());
		eventReport.setReportUser(this.getMyAccount().getUser());
		List<Option> o = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
		if (o.size() > 0) {
			eventReport.setReportEventVariable(o.get(0));
			reportTask.setEventTaskState(o.get(0));
			reportTask.setEventTaskOperate("初始化事件源");
		}
		o = this.optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
		if (o.size() > 0) {
			eventReport.setReportEventAttrVariable(o.get(0));
		}

		// 获取事件所属网格,遗留
		GridAreaInfo info = this.gridAreaInfoService.GetGridAreaInfoByCoordinate(eventReport.getLongitude(),
				eventReport.getLatitude());
		eventReport.setReportEventToNetGrid(info);

		List<EventRegister> dlist = new ArrayList<>();
		List<EventTask> registerTasklist = new ArrayList<>();

		JSONArray eventRegisterList = JSONArray.fromObject(request.getParameter("eventRegister"));
		List<Option> options = this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "初始化");
		for (int i = 0; i < eventRegisterList.size(); i++) {
			JSONObject jsonObject = eventRegisterList.getJSONObject(i);
			EventRegister eventRegister = (EventRegister) JSONObject.toBean(jsonObject, EventRegister.class);
			file = requests.getFile(eventRegister.getRegisterEventType().getId());

			if (file != null && !file.isEmpty()) {
				// 注意路径的构建
				url = getUploadFilePath(this.fileUploadPath, "img/eventRegister", file);
				eventRegister.setRegisterEventImgAdress(url);
			}
			// 前端图片压缩上传功能
			else if (eventRegister.getRegisterEventImgAdress() != null
					&& eventRegister.getRegisterEventImgAdress().contains("data:image/png;base64")) {
				String[] imgl = eventRegister.getRegisterEventImgAdress().split(",");
				url = this.saveImgWithBase64(this.fileUploadPath, "img/eventRegister", eventRegister.getId() + ".png",
						imgl[imgl.length - 1]);
				eventRegister.setRegisterEventImgAdress(url);
			}
			// -----------------------
			// 设置事件登记其他信息
			eventRegister.setRegisterEventCreateUser(this.getMyAccount().getUser());
			eventRegister.setRegisterEventToReportEvent(eventReport);
			eventRegister.setRegisterEventAccTime(DateTime.now().toDate());
			eventRegister.setRegisterEventReportTime(DateTime.now().toDate());
			EventTask registerTask = new EventTask();
			registerTask.setEventId(eventRegister.getId());
			if (options.size() > 0) {
				eventRegister.setRegisterEventState(options.get(0));
				registerTask.setEventTaskState(options.get(0));
			}

			// 事件所属网格，遗留
			eventRegister.setRegisterEventToNetGrid(info);
			// 获取事件编码
			String areaId = "";
			if (info != null && info.getDivision() != null) {
				areaId = info.getDivision().getId();
			}
			String eventTypeId = "";
			if (eventRegister.getRegisterEventType() != null) {
				eventTypeId = eventRegister.getRegisterEventType().getId();
			}
			String registerEventIdentify = this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventTypeId);
			eventRegister.setRegisterEventIdentify(registerEventIdentify);

			// 当部件不为空时候，需要关联组织

			dlist.add(eventRegister);

			if (!eventReport.getReportEventVariable().getTitle().equals("已受理")) {
				o = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
				if (o.size() > 0) {
					eventReport.setReportEventVariable(o.get(0));
					reportTask.setEventTaskState(o.get(0));
					reportTask.setEventTaskOperate("受理事件源");
				}
			}

			registerTask.setEventTaskTime(DateTime.now().toDate());
			registerTask.setEventTaskUser(this.getMyAccount().getUser());
			registerTask.setEventTaskMemo(eventRegister.getRegisterEventMemo());
			registerTask.setEventTaskOperate("初始化内部事件");
			registerTasklist.add(registerTask);
		}

		this.eventReportService.saveAll(eventReport, dlist, reportTask, registerTasklist);

		code = 1;
		map.put("code", code);
		try {
			if (eventReport.getReportEventVariable().getTitle().equals("初始化")) {
				if (AppWebSocketTask.webSocketSet != null) {
					SocketMessage message = new SocketMessage();
					message.setOnlinePerson(null);
					for (AppWebSocketTask item : AppWebSocketTask.webSocketSet) {
						try {
							if (item.getLocation().equals("header")) {
								if (item.isShow(item.getAid(), "eventRegister")) {
									message.setDealEventOverTime(null);
									message.setReceiveEventOverTime(null);
									message.setRejectConfirm(null);
									message.setWaitingPublic(null);
									message.setWaitingAccept(Integer.toString(this.eventReportService
											.getWaitingAcceptEventCountByAccount(item.getAid())));
									item.sendMessage(JSONObject.fromObject(message).toString());
								}
							} else if (item.getLocation().equals("eventReport")) {
								message.setRefreahEventReport("true");
								message.setDealEventOverTime(null);
								message.setReceiveEventOverTime(null);
								message.setRejectConfirm(null);
								message.setWaitingPublic(null);
								message.setWaitingAccept(null);
								item.sendMessage(JSONObject.fromObject(message).toString());
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception ex) {

		}
		return map;
	}

	@RequestMapping(value = "/saveReportAndRegisterEventWithoutInputFile", method = RequestMethod.POST)
	public Map<String, Object> saveReportAndRegisterEventWithoutInputFile() {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;

		// 获取当前EventReport图片的存储路径
		String url = "";
		JSONObject project = JSONObject.fromObject(request.getParameter("eventReport"));
		EventReport eventReport = (EventReport) JSONObject.toBean(project, EventReport.class);
		
		//设置真实是事件类型
		eventReport.setRealReportEventType(eventReport.getReportEventType());
		
		//标注事件来源
		Option org=this.optionService.getRepository().findByGroupAndExtended1("事件上报来源", "移动端");
		if(org!=null){
			eventReport.setReportEventOrg(org);
		}
		//------------
		// 前端图片压缩上传功能
		if (eventReport.getReportImgAdress() != null
				&& eventReport.getReportImgAdress().contains("data:image/png;base64")) {
			String[] imgl = eventReport.getReportImgAdress().split(",");
			eventReport.setReportImgAdress("");
			url = this.saveImgWithBase64(this.fileUploadPath, "img/eventReport", eventReport.getId() + ".png",
					imgl[imgl.length - 1]);
		}
		// -----------------------

		EventTask reportTask = null;
		if (this.eventRegisterService.getRepository().findOne(eventReport.getId()) == null) {
			reportTask = new EventTask();
			reportTask.setEventId(eventReport.getId());
			reportTask.setEventTaskTime(DateTime.now().toDate());
			reportTask.setEventTaskUser(this.getMyAccount().getUser());
		}

		// 设置事件上报其他信息.
		eventReport.setReportImgAdress(url);
		eventReport.setReportAccTime(DateTime.now().toDate());
		eventReport.setReportUser(this.getMyAccount().getUser());
		List<Option> o = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
		if (o.size() > 0) {
			eventReport.setReportEventVariable(o.get(0));
			reportTask.setEventTaskState(o.get(0));
			reportTask.setEventTaskOperate("初始化事件源");
		}
		o = this.optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
		if (o.size() > 0) {
			eventReport.setReportEventAttrVariable(o.get(0));
		}

		// 获取事件所属网格,遗留
		GridAreaInfo info = this.gridAreaInfoService.GetGridAreaInfoByCoordinate(eventReport.getLongitude(),
				eventReport.getLatitude());
		eventReport.setReportEventToNetGrid(info);

		List<EventRegister> dlist = new ArrayList<>();
		List<EventTask> registerTasklist = new ArrayList<>();
		boolean isMessageToReport =false;

		JSONArray eventRegisterList = JSONArray.fromObject(request.getParameter("eventRegister"));
		List<Option> options = this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "初始化");
		for (int i = 0; i < eventRegisterList.size(); i++) {
			JSONObject jsonObject = eventRegisterList.getJSONObject(i);
			EventRegister eventRegister = (EventRegister) JSONObject.toBean(jsonObject, EventRegister.class);

			// 前端图片压缩上传功能
		    if (eventRegister.getRegisterEventImgAdress() != null
					&& eventRegister.getRegisterEventImgAdress().contains("data:image/png;base64")) {
				String[] imgl = eventRegister.getRegisterEventImgAdress().split(",");
				url = this.saveImgWithBase64(this.fileUploadPath, "img/eventRegister", eventRegister.getId() + ".png",
						imgl[imgl.length - 1]);
				eventRegister.setRegisterEventImgAdress(url);
			}
			// -----------------------
			// 设置事件登记其他信息
			eventRegister.setRegisterEventCreateUser(this.getMyAccount().getUser());
			eventRegister.setRegisterEventToReportEvent(eventReport);
			eventRegister.setRegisterEventAccTime(DateTime.now().toDate());
			eventRegister.setRegisterEventReportTime(DateTime.now().toDate());
			EventTask registerTask = new EventTask();
			registerTask.setEventId(eventRegister.getId());
			if (options.size() > 0) {
				eventRegister.setRegisterEventState(options.get(0));
				registerTask.setEventTaskState(options.get(0));
			}

			// 事件所属网格，遗留
			eventRegister.setRegisterEventToNetGrid(info);
			// 获取事件编码
			String areaId = "";
			if (info != null && info.getDivision() != null) {
				areaId = info.getDivision().getId();
			}
			String eventTypeId = "";
			if (eventRegister.getRegisterEventType() != null) {
				eventTypeId = eventRegister.getRegisterEventType().getId();
			}
			String registerEventIdentify = this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventTypeId);
			eventRegister.setRegisterEventIdentify(registerEventIdentify);

			// 当部件不为空时候，需要关联组织

			dlist.add(eventRegister);

			if (!eventReport.getReportEventVariable().getTitle().equals("已受理")) {
				o = this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
				if (o.size() > 0) {
					eventReport.setReportEventVariable(o.get(0));
					reportTask.setEventTaskState(o.get(0));
					reportTask.setEventTaskOperate("受理事件源");
				}
			}

			registerTask.setEventTaskTime(DateTime.now().toDate());
			registerTask.setEventTaskUser(this.getMyAccount().getUser());
			registerTask.setEventTaskMemo(eventRegister.getRegisterEventMemo());
			registerTask.setEventTaskOperate("初始化内部事件");
			registerTasklist.add(registerTask);
			isMessageToReport=true;
		}

		this.eventReportService.saveAll(eventReport, dlist, reportTask, registerTasklist);

		code = 1;
		map.put("code", code);
		try {
			if (eventReport.getReportEventVariable().getTitle().equals("初始化")) {
				if (AppWebSocketTask.webSocketSet != null) {
					SocketMessage message = new SocketMessage();
					message.setOnlinePerson(null);
					for (AppWebSocketTask item : AppWebSocketTask.webSocketSet) {
						try {
							if (item.getLocation().equals("header")) {
								if (item.isShow(item.getAid(), "eventRegister")) {
									message.setDealEventOverTime(null);
									message.setReceiveEventOverTime(null);
									message.setRejectConfirm(null);
									message.setWaitingPublic(null);
									message.setWaitingAccept(Integer.toString(this.eventReportService
											.getWaitingAcceptEventCountByAccount(item.getAid())));
									item.sendMessage(JSONObject.fromObject(message).toString());
								}
							} else if (item.getLocation().equals("eventReport")) {
								message.setRefreahEventReport("true");
								message.setDealEventOverTime(null);
								message.setReceiveEventOverTime(null);
								message.setRejectConfirm(null);
								message.setWaitingPublic(null);
								message.setWaitingAccept(null);
								item.sendMessage(JSONObject.fromObject(message).toString());
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception ex) {

		}
		if(isMessageToReport){
			for(int i=0;i<dlist.size();i++){
			//------------
			//短信通知扣分者
			sendMsgToMarksUser(dlist.get(i));
			//----
			}
		}
		return map;
	}
	// 获得本月第一天0点时间  
    public static Date getTimesMonthmorning() {  
        Calendar cal = Calendar.getInstance();  
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);  
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));  
        return  cal.getTime();  
    } 
    /**
     * 案件扣分通知
     * @param eventRegister
     */
	private void sendMsgToMarksUser(EventRegister eventRegister){
		try {
			List<EventToEvaluateUser> dlist=this.eventToEvaluateUserService.getRepository().findListByEventRegister(eventRegister.getId());
			if (dlist != null) {
				for (int i = 0; i < dlist.size(); i++) {
					String phoneList = "";
					double scaleForMonth = 0;
					if (dlist.get(i).getRegisterUser() != null) {
						phoneList = dlist.get(i).getRegisterUser().getContactType();
						scaleForMonth = this.eventToEvaluateUserService.getUserMarkScoreByDate(
								dlist.get(i).getRegisterUser().getId(), getTimesMonthmorning(),
								DateTime.now().toDate());
					}
					if (phoneList != "") {
						// 短信通知
						String content = "【悦来城市综合服务平台】案件发生，案件["
								+ dlist.get(i).getRegisterEvent().getRegisterEventIdentify() + "]已确认。根据塔型压力扣分机制，该案件扣["
								+ dlist.get(i).getScale() + "]，当月累计扣分[" + scaleForMonth + "]分。";

						Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "案件扣分通知");
						if (op != null) {
							content = op.getTitle();
						}
						content = content.replace("{0}", dlist.get(i).getRegisterEvent().getRegisterEventIdentify());
						content = content.replace("{1}", Double.toString(dlist.get(i).getScale()));
						content = content.replace("{2}", Double.toString(scaleForMonth));
						Map<String, Object> mapTemp = this.sendMessage(phoneList, content);
						if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
							// 是否记录日志
							operateLogService.log(this.getMyAccount().getUser(), "案件扣分通知", content);
						} else {
							operateLogService.log(this.getMyAccount().getUser(), "案件扣分通知", "发送案件扣分通知失败!");
						}
						// ------------
					}
				}
			}
		} catch (Exception ex) {

		}
	}
	/**
	 * 初始化页面
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {

		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");// 用户部件上报中部件的identify
		String eventType = request.getParameter("eventType");
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/event/mobileEventReport");//
			modelAndView.addObject("identify", identify);
			modelAndView.addObject("device", device);
			modelAndView.addObject("type", eventType);

			List<EventType> eventTypes = this.eventTypeService.getRepository().getEventTypesByParent("0");
			/*
			 * List<Grading> registerEventEvaluateLevels =
			 * this.gradingService.getRepository().findAllNodes();
			 */
			List<Option> registerEventSeriousLevels = this.optionService.getRepository().findByGroup("事件严重等级");
			modelAndView.addObject("eventTypes", eventTypes);
			/*
			 * modelAndView.addObject("registerEventEvaluateLevels",
			 * registerEventEvaluateLevels);
			 */
			modelAndView.addObject("registerEventSeriousLevels", registerEventSeriousLevels);
			modelAndView.addObject("user", getMyAccount().getUser());
		} else {
			// PC端
			List<Option> reportEventAttrVariables = this.optionService.getRepository().findByGroup("事件上报属性状态");
			modelAndView = createLayoutView("eventReport/eventReport");
			modelAndView.addObject("reportEventAttrVariables", reportEventAttrVariables);
		}
		return modelAndView;
	}

	@RequestMapping(value = "getpage/{eventVariable}", method = RequestMethod.GET)
	public Map<String, Object> getPage(@PathVariable("eventVariable") String eventVariable,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		// String eventVariable="初始化";

//		List<EventReport> eventReport = this.eventReportService.getPageByEventVariable(start, length, key, eventVariable, "reportAccTime", Sort.Direction.DESC);
//		int count = this.eventReportService.getCountByEventVariable(key, eventVariable);
		
		String roleId = this.getMyAccount().getRole().getId();
		List<Map<String,Object>> eventReport = this.eventReportService.getPageByEventVariableAndRole(start, length, roleId, key, eventVariable, "reportAccTime", "DESC");
		int count = this.eventReportService.getCountByEventVariableAndRole(roleId,key, eventVariable);
		
		
		map.put("data", eventReport);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "getpagebyview/{eventVariable}", method = RequestMethod.GET)
	public Map<String, Object> getpagebyview(@PathVariable("eventVariable") String eventVariable,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");

//		List<ViewForEventReportTask> eventReport = this.eventReportService.getViewForEventReportTaskPageByEventVariable(start, length, key, eventVariable, "reportAccTime", Sort.Direction.DESC);
//		int count = this.eventReportService.getViewForEventReportTaskCountByEventVariable(key, eventVariable);

		String roleId = this.getMyAccount().getRole().getId();
		List<Map<String, Object>> eventReport = this.eventReportService.getViewForEventReportTaskPageByEventVariableAndRole(start, length, roleId, key, eventVariable, "reportAccTime", "DESC");
		int count = this.eventReportService.getViewForEventReportTaskCountByEventVariableAndRole(roleId, key, eventVariable);
		
		map.put("data", eventReport);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "finishEventReport", method = RequestMethod.POST)
	public MsgHelper finishEventReport(@RequestBody Map<String, Object> request) {
		String id = (String) request.get("id");
		String finishMemo = (String) request.get("finishMemo");
		String reportEventAttrVariable = (String) request.get("reportEventAttrVariable");
		this.eventReportService.finishEventReport(id, finishMemo, reportEventAttrVariable,
				this.getMyAccount().getUser());
		Option findOne = optionService.getRepository().findOne(reportEventAttrVariable);
		if (findOne != null) {
			if ("重复上报".equals(findOne.getTitle())) {
				MessageToReportUser(id);
			}
		}

		return MsgHelper.success().put("code", 1);
	}

	private void MessageToReportUser(String id) {
		EventReport eventReport = this.eventReportService.getRepository().getOne(id);
		if (eventReport != null) {
			String reportTime = eventReport.getReportAccTime().toString();
			String phone = eventReport.getReportUser().getContactType();
			String eventType = eventReport.getReportEventType().getEventName();
			// 短信通知上报者
			String content = "【悦来城市综合服务平台】您于[" + reportTime + "]上报的[" + eventType + "]事件属于重复上报事件，感谢您的支持!";

			Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "重复上报通知");
			if (op != null) {
				content = op.getTitle();
			}
			content = content.replace("{0}", reportTime);
			content = content.replace("{1}", eventType);
			Map<String, Object> mapTemp = this.sendMessage(phone, content);
			if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
				// 是否记录日志
				operateLogService.log(this.getMyAccount().getUser(), "重复上报通知", content);
			} else {
				operateLogService.log(this.getMyAccount().getUser(), "重复上报通知", "发送重复上报通知消息失败!");
			}
		}
	}

	@RequestMapping(value = "getRealTimeEventIdentify", method = RequestMethod.GET)
	public MsgHelper getRealTimeEventIdentify() {

		String eventTypeId = (String) request.getParameter("eventTypeId");
		double longitude = Double.parseDouble(request.getParameter("longitude"));
		double latitude = Double.parseDouble(request.getParameter("latitude"));

		GridAreaInfo info = this.gridAreaInfoService.GetGridAreaInfoByCoordinate(longitude, latitude);
		MsgHelper helper = MsgHelper.success().put("codeForGrid", 1);
		helper.put("gridInfo", info);

		String areaId = "";
		if (info != null && info.getDivision() != null) {
			areaId = info.getDivision().getId();
		}
		try {
			String eventIdentify = this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventTypeId);
			helper.put("codeForEventIdentify", 1);
			helper.put("eventIdentify", eventIdentify);
			return helper;
		} catch (Exception ex) {
			return helper.put("codeForEventIdentify", -1);
		}

	}

	@RequestMapping(value = "/getReports/{eventVariable}", method = RequestMethod.POST)
	public Map<String, Object> getReports(@PathVariable("eventVariable") String eventVariable) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<EventReport> reports = this.eventReportService.getEventReportByEventVariable(eventVariable);
		map.put("reports", reports);
		return map;
	}

	@RequestMapping(value = "/transfer/{realEventTypeId}/{reportId}", method = RequestMethod.POST)
	public Map<String, Object> transfer(@PathVariable("realEventTypeId") String realEventTypeId,@PathVariable("reportId") String reportId) {
		Map<String, Object> map = new HashMap<String, Object>();
		EventReport eventReport = eventReportService.getRepository().findOne(reportId);
		EventType oldEventType = eventReport.getReportEventType();
		EventType realEventType = eventTypeService.getRepository().findOne(realEventTypeId);
		eventReport.setRealReportEventType(realEventType);
		eventReportService.getRepository().save(eventReport);
		
		TransferTask task = new TransferTask();
		task.setEventId(reportId);
		task.setEventTaskUser(this.getMyAccount().getUser());
		task.setEventTaskTime(new Date());
		String eventTaskOperate = "上报事件源转办";
		String eventTaskMemo = "由<" + oldEventType.getEventName() + ">转办至<" + realEventType.getEventName() + ">。";
		task.setEventTaskOperate(eventTaskOperate);
		task.setEventTaskMemo(eventTaskMemo);
		transferTaskService.getRepository().save(task);
		map.put("code", 1);
		map.put("msg", "事件源转办成功！");
		
		return map;
	}
	
	/**
	 * 显示区域结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<EventType> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = eventTypeService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=eventTypeService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
}
